//
//  Router.swift
//  RX
//
//  Created by iOS开发 on 2019/2/13.
//  Copyright © 2019 iOS开发. All rights reserved.
//

import UIKit
import Alamofire

enum Router {
    static let baseURL = "http://jsonplaceholder.typicode.com"
    
    case get(Int?)
    case post([String : Any])
    
    func asURLRequest() -> URLRequest {
        var method : HTTPMethod {
            switch self {
            case .get:
                return .get
            case .post:
                return .post
            }
        }
        
        var params:[String : Any]? {
            switch self {
            case .get:
                return nil
            case .post:
                return [:]
            }
        }
        
        var url : URL {
            var relativeURL = "todos"
            
            switch self {
            case .get(let todoID):
                if todoID != nil {
                    relativeURL += "/\(String(describing: todoID))"
                }
                break
            case .post:
                break
            }
            
            let url = URL(string: Router.baseURL)!.appendingPathComponent(relativeURL)
            return url
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = method.rawValue
        let encoding = JSONEncoding.default
        
        return try! encoding.encode(request,with: params)
    }
    
}
